﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
using Common.BaseLibrary.Authorization;
using Common.BaseLibrary.Config;
using Common.BaseLibrary.Logger;
using Common.BaseLibrary.Utils;
using DepartmentWork.Migrator.Data;
using DepartmentWork.Model;
using DepartmentWork.Platform.Controllers;
using Spire.Doc;

namespace DepartmentWork.Platform.Areas.ProjectManageArea.Controllers
{
    public class MonthlyController : BaseController
    {
        //
        // GET: /ProjectManageArea/Monthly/

        public ActionResult Index(string flag = "", string info = "")
        {

            #region 校验身份

            ViewBag.IsAdmin = false;
            string[] pathArr = Request.Path.Split('/');
            try
            {
                Guid userGuid = new Guid(CurrentUser.UserID);
                USER_INFO userAdmin = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == userAdmin.USER_ID).FirstOrDefault();
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == "Project")
                    {
                        ViewBag.IsAdmin = true;
                        //break;
                    }
                }
            }
            catch (Exception)
            {
                ViewBag.IsAdmin = false;
            }
            
            #endregion

            ViewBag.flag = flag;
            ViewBag.info = info;

            MonthlyViewModel model = new MonthlyViewModel();

            model.ProjectWorkReocredList = new List<ProjectWorkReocredInfoViewModel>();
            model.ProjectManitenanceRecordList = new List<ProjectManintenanceRecordViewModel>();
            model.ProjectManitenanceAppopsList = new List<ProjectManintenanceAppopsViewModel>();
            model.ProjectManagementList = new List<ProjectManagementInfoViewModel>();
            model.FileList = new List<FileViewModel>();

            #region 注释内容（2017-05-03 修改）

            #region 添加项目

            //List<PROJECT_MANAGEMENT> projectManagementsList = projectManagementRepository.GetModel().ToList();
            //if (projectManagementsList.Count() != 0)
            //{
            //    model.ProjectManagementList.AddRange((from item in projectManagementsList
            //                                          select new ProjectManagementInfoViewModel()
            //                                          {
            //                                              PROJECT_MANAGEMENT_ID = item.PROJECT_MANAGEMENT_ID,
            //                                              PROJECT_MANAGEMENT_TITLE = item.PROJECT_MANAGEMENT_TITLE,
            //                                              PROJECT_MANAGEMENT_CREATETIME = item.PROJECT_MANAGEMENT_CREATETIME
            //                                          }).ToList());
            //}

            #endregion

            #region 添加工作记录

            //if (model.ProjectManagementList.Count() != 0)
            //{
            //    for (int i = 0; i < model.ProjectManagementList.Count(); i++)
            //    {
            //        Guid proId = model.ProjectManagementList[i].PROJECT_MANAGEMENT_ID;



            //        List<PROJECT_WORKRECORD> proWordList = projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == proId).ToList();

            //        if (proWordList.Count() != 0)
            //        {
            //            for (int j = 0; j < proWordList.Count(); j++)
            //            {
            //                ProjectWorkReocredInfoViewModel workReocredInfo = new ProjectWorkReocredInfoViewModel();
            //                workReocredInfo.PROJECT_MANAGEMENT_ID = proWordList[j].PROJECT_MANAGEMENT_ID;
            //                workReocredInfo.PROJECT_WORKRECORD_ID = proWordList[j].PROJECT_WORKRECORD_ID;
            //                workReocredInfo.PROJECT_WORKRECORD_TITLE = proWordList[j].PROJECT_WORKRECORD_TITLE;
            //                workReocredInfo.PROJECT_WORKRECORD_CREATETIME = proWordList[j].PROJECT_WORKRECORD_CREATETIME;
            //                model.ProjectWorkReocredList.Add(workReocredInfo);
            //            }
            //        }
            //    }
            //}

            #endregion

            #region 添加运维项目

            //List<PROJECT_MAINTENANCE_APPOPS> maintenamceAppList = projectMaintenanceAppopsRepository.GetModel().ToList();

            //if (maintenamceAppList.Count() != 0)
            //{
            //    model.ProjectManitenanceAppopsList.AddRange((from item in maintenamceAppList
            //                                                 select new ProjectManintenanceAppopsViewModel()
            //                                                 {
            //                                                     appops_id = item.APPOPS_ID,
            //                                                     appops_name = item.APPOPS_NAME,
            //                                                     appops_time = item.APPOPS_TIME
            //                                                 }).ToList());
            //}

            #endregion

            #region 添加运维项目记录

            //if (model.ProjectManitenanceAppopsList.Count() != 0)
            //{
            //    for (int i = 0; i < model.ProjectManitenanceAppopsList.Count(); i++)
            //    {
            //        Guid proId = model.ProjectManitenanceAppopsList[i].appops_id;
            //        List<PROJECT_MAINTENANCE_RECORD> workReocredInfoList = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_OPERATION_ID == proId).ToList();

            //        for (int j = 0; j < workReocredInfoList.Count(); j++)
            //        {
            //            ProjectManintenanceRecordViewModel recored = new ProjectManintenanceRecordViewModel();
            //            recored.record_operation_id = workReocredInfoList[j].RECORD_OPERATION_ID;
            //            recored.record_id = workReocredInfoList[j].RECORD_ID;
            //            recored.record_name = workReocredInfoList[j].RECORD_NAME;
            //            recored.record_time = workReocredInfoList[j].RECORD_TIME;
            //            model.ProjectManitenanceRecordList.Add(recored);
            //        }
            //    }
            //}

            #endregion

            #endregion

            #region 获取月报的所有的文档

            ViewBag.MonthlyCount = fileRepository.GetModel(
                r => r.FILE_TYPE == "PROJECT_MANAGEMENT_MONTHLY").Count(); ;

            List<FILEINFO> filesList = fileRepository.GetModel(
                r => r.FILE_TYPE == "PROJECT_MANAGEMENT_MONTHLY").OrderByDescending(r => r.FILE_CREATETIME).ToList();

            model.FileList.AddRange((from item in filesList
                                     select new FileViewModel()
                                     {
                                         CONTACT_ID = item.CONTACT_ID,
                                         FILE_CREATER = item.FILE_CREATER,
                                         FILE_ID = item.FILE_ID,
                                         FILE_SAVENAME = item.FILE_SAVENAME,
                                         FILE_SAVEPATH = item.FILE_SAVEPATH,
                                         FILE_SHOWNAME = item.FILE_SHOWNAME,
                                         FILE_TYPE = item.FILE_TYPE
                                     }).ToList());

            #endregion

            return View(model);
        }


        [HttpGet]
        public ActionResult CreateMonthly(string flag = "", string info = "")
        {
            #region 校验身份

            ViewBag.IsAdmin = false;
            string[] pathArr = Request.Path.Split('/');
            try
            {
                Guid userGuid = new Guid(CurrentUser.UserID);
                USER_INFO userAdmin = userRepository.GetModel(r => r.USER_ID == userGuid).FirstOrDefault();
                USER_TEAMSAPCE userTeam = userTeamsapceRepository.GetModel(r => r.USER_ID == userAdmin.USER_ID).FirstOrDefault();
                ROLE_INFO role = roleRepository.GetModel(r => r.ROLE_ID == userTeam.ROLE_ID).FirstOrDefault();
                List<MENU_ROLE> menuRole = menuRoleRepository.GetModel(r => r.ROLE_ID == role.ROLE_ID).ToList();
                for (int i = 0; i < menuRole.Count(); i++)
                {
                    int menuId = menuRole[i].MENU_ID;
                    MENU menu = menuRepository.GetModel(r => r.MENU_ID == menuId).FirstOrDefault();
                    if (menu.AREA_NAME == pathArr[2] && menu.CONTROLLER_NAME == "Project")
                    {
                        ViewBag.IsAdmin = true;
                        //break;
                    }
                }
            }
            catch (Exception)
            {
                ViewBag.IsAdmin = false;
            }

            #endregion

            ViewBag.flag = flag;
            ViewBag.info = info;

            MonthlyViewModel model = new MonthlyViewModel();

            model.ProjectWorkReocredList = new List<ProjectWorkReocredInfoViewModel>();
            model.ProjectManitenanceRecordList = new List<ProjectManintenanceRecordViewModel>();
            model.ProjectManitenanceAppopsList = new List<ProjectManintenanceAppopsViewModel>();
            model.ProjectManagementList = new List<ProjectManagementInfoViewModel>();
            model.FileList = new List<FileViewModel>();

            #region 添加项目

            List<PROJECT_MANAGEMENT> projectManagementsList = projectManagementRepository.GetModel().ToList();
            if (projectManagementsList.Count() != 0)
            {
                model.ProjectManagementList.AddRange((from item in projectManagementsList
                                                      select new ProjectManagementInfoViewModel()
                                                      {
                                                          PROJECT_MANAGEMENT_ID = item.PROJECT_MANAGEMENT_ID,
                                                          PROJECT_MANAGEMENT_TITLE = item.PROJECT_MANAGEMENT_TITLE,
                                                          PROJECT_MANAGEMENT_CREATETIME = item.PROJECT_MANAGEMENT_CREATETIME
                                                      }).ToList());
            }

            #endregion

            #region 添加工作记录

            if (model.ProjectManagementList.Count() != 0)
            {
                for (int i = 0; i < model.ProjectManagementList.Count(); i++)
                {
                    Guid proId = model.ProjectManagementList[i].PROJECT_MANAGEMENT_ID;



                    List<PROJECT_WORKRECORD> proWordList = projectWorkReocredRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == proId).ToList();

                    if (proWordList.Count() != 0)
                    {
                        for (int j = 0; j < proWordList.Count(); j++)
                        {
                            ProjectWorkReocredInfoViewModel workReocredInfo = new ProjectWorkReocredInfoViewModel();
                            workReocredInfo.PROJECT_MANAGEMENT_ID = proWordList[j].PROJECT_MANAGEMENT_ID;
                            workReocredInfo.PROJECT_WORKRECORD_ID = proWordList[j].PROJECT_WORKRECORD_ID;
                            workReocredInfo.PROJECT_WORKRECORD_TITLE = proWordList[j].PROJECT_WORKRECORD_TITLE;
                            workReocredInfo.PROJECT_WORKRECORD_CREATETIME = proWordList[j].PROJECT_WORKRECORD_CREATETIME;
                            model.ProjectWorkReocredList.Add(workReocredInfo);
                        }
                    }
                }
            }

            #endregion

            #region 添加运维项目

            List<PROJECT_MAINTENANCE_APPOPS> maintenamceAppList = projectMaintenanceAppopsRepository.GetModel().ToList();

            if (maintenamceAppList.Count() != 0)
            {
                model.ProjectManitenanceAppopsList.AddRange((from item in maintenamceAppList
                                                             select new ProjectManintenanceAppopsViewModel()
                                                             {
                                                                 appops_id = item.APPOPS_ID,
                                                                 appops_name = item.APPOPS_NAME,
                                                                 appops_time = item.APPOPS_TIME
                                                             }).ToList());
            }

            #endregion

            #region 添加运维项目记录

            if (model.ProjectManitenanceAppopsList.Count() != 0)
            {
                for (int i = 0; i < model.ProjectManitenanceAppopsList.Count(); i++)
                {
                    Guid proId = model.ProjectManitenanceAppopsList[i].appops_id;
                    List<PROJECT_MAINTENANCE_RECORD> workReocredInfoList = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_OPERATION_ID == proId).ToList();

                    for (int j = 0; j < workReocredInfoList.Count(); j++)
                    {
                        ProjectManintenanceRecordViewModel recored = new ProjectManintenanceRecordViewModel();
                        recored.record_operation_id = workReocredInfoList[j].RECORD_OPERATION_ID;
                        recored.record_id = workReocredInfoList[j].RECORD_ID;
                        recored.record_name = workReocredInfoList[j].RECORD_NAME;
                        recored.record_time = workReocredInfoList[j].RECORD_TIME;
                        model.ProjectManitenanceRecordList.Add(recored);
                    }
                }
            }

            #endregion



            return this.View(model);

        }



        [HttpPost]
        public ActionResult CreateMonthly(FormCollection collection)
        {
            string fileShowName = collection["select_year"] + "年" + collection["select_month"]+"月的月报";

            Guid proId = Guid.NewGuid();
            FILEINFO file = new FILEINFO();
            int fileCount = this.Request.Files.Count;
            HttpPostedFile[] upFiles = new HttpPostedFile[fileCount];
            string temp = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Monthly\";
            this.Request.Files.CopyTo(upFiles, 0);
            if (upFiles[0].FileName != "")
            {
                try
                {
                    string fileSaveName = string.Empty;
                    HttpPostedFile hpf;
                    hpf = upFiles[0];
                    string fullUpLoadPath = "";
                    Guid fileName = Guid.NewGuid();
                    fileSaveName = string.Format("{0}{1}", fileName, Path.GetExtension(hpf.FileName));
                    fullUpLoadPath = Path.Combine(temp, fileSaveName);
                    hpf.SaveAs(Path.Combine(fullUpLoadPath));

                    file.FILE_ID = fileName;
                    //file.FILE_SHOWNAME = upFiles[0].FileName.Split('\\')[upFiles[0].FileName.Split('\\').Length - 1];
                    file.FILE_SHOWNAME = fileShowName;
                    file.FILE_SAVEPATH = fullUpLoadPath;
                    file.FILE_SAVENAME = fileSaveName;
                    file.FILE_CREATETIME = DateTime.Now;
                    //file.FILE_CREATER = new Guid(CurrentUser.UserID);
                    //file.FILE_TYPE = "DEVELOP_BUG";
                    //file.CONTACT_ID = bugModel.BUG_ID;
                    file.CONTACT_ID = proId;
                    file.FILE_CREATER = new Guid(CurrentUser.UserID);
                    file.FILE_TYPE = "PROJECT_MANAGEMENT_MONTHLY";
                    fileRepository.Insert(file);
                    LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "月报上传");

                    return this.RedirectToAction("Index", "Monthly", new { area = "ProjectManageArea", flag = "CreateTrue" });

                }
                catch (Exception ex)
                {
                    LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "月报上传失败！ 信息：" + ex.Message);

                    return this.RedirectToAction("Index", "Monthly", new { area = "ProjectManageArea", flag = "CreateFalse", info = ex.Message });
                }
            }
            return this.RedirectToAction("Index", "Monthly", new { area = "ProjectManageArea", flag = "CreateFalse", info = ""});
        }

        public ActionResult DelMonthly(Guid monthlyId, Guid proId)
        {
            try
            {
                FILEINFO file = fileRepository.GetModel(r => r.FILE_ID == monthlyId && r.FILE_TYPE == "PROJECT_MANAGEMENT_MONTHLY")
                .FirstOrDefault();
                fileRepository.Delete(file);
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "删除月报模板");
                return this.RedirectToAction("Index", "Monthly", new { area = "ProjectManageArea", flag = "DelTrue", projectId = proId });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName + " " + DateTime.Now + " " + "删除月报模板失败！ 信息：" + ex.Message);
                return this.RedirectToAction("Index", "Monthly", new { area = "ProjectManageArea", flag = "DelFalse", info = ex.Message });
            }
        }

        [HttpPost]
        public ActionResult ExecuteCreateMonthly(FormCollection collection)
        {
            string fileShowName = collection["select_year"] + "年" + collection["select_month"] + "月";

            try
            {
                Document document = new Document();

                document.LoadFromFile(ConfigurationManager.AppSettings["UpLoadPath"] + @"\Monthly\Templete.doc");

                string[] arr = collection["ck_AllProject"].Split(',');

                List<Guid> proWorkIdList = new List<Guid>();//工作记录ID

                List<Guid> yunWeiWorkIdList = new List<Guid>();//运维记录ID

                //获取全部选中的 工作记录ID 和 运维记录ID
                for (int i = 0; i < arr.Length; i++)
                {
                    string temp = arr[i].Split('_')[1];
                    if (arr[i].Split('_')[0].Contains("Pro"))
                    {

                        proWorkIdList.Add(new Guid(temp));
                    }
                    else
                    {
                        yunWeiWorkIdList.Add(new Guid(temp));
                    }
                }

                List<PROJECT_WORKRECORD> proWorkListTemp = new List<PROJECT_WORKRECORD>();
                List<PROJECT_MAINTENANCE_RECORD> yunWeiWorkListTemp = new List<PROJECT_MAINTENANCE_RECORD>();


                for (int i = 0; i < proWorkIdList.Count(); i++)
                {
                    Guid pWorkId = proWorkIdList[i];
                    PROJECT_WORKRECORD work = projectWorkReocredRepository.GetModel(r => r.PROJECT_WORKRECORD_ID == pWorkId).FirstOrDefault();
                    if (work != null)
                    {
                        proWorkListTemp.Add(work);
                    }
                }

                for (int i = 0; i < yunWeiWorkIdList.Count(); i++)
                {
                    Guid pId = yunWeiWorkIdList[i];
                    PROJECT_MAINTENANCE_RECORD record = projectMaintenanceRecordRepository.GetModel(r => r.RECORD_ID == pId).FirstOrDefault();
                    if (record != null)
                    {
                        yunWeiWorkListTemp.Add(record);
                    }
                }

                List<PROJECT_WORKRECORD> proWorkList = proWorkListTemp.OrderBy(r => r.PROJECT_WORKRECORD_ID).ToList();
                List<PROJECT_MAINTENANCE_RECORD> yunWeiWorkList = yunWeiWorkListTemp.OrderBy(r => r.RECORD_ID).ToList();
                string msgPro = "";
                int flag = 1;

                #region 项目管理 写入WORD

                PROJECT_MANAGEMENT proOld = new PROJECT_MANAGEMENT();
                PROJECT_MANAGEMENT proNew = new PROJECT_MANAGEMENT();
                for (int i = 0; i < proWorkList.Count(); i++)
                {
                    if (i == 0)
                    {
                        Guid? pId = proWorkList[i].PROJECT_MANAGEMENT_ID;
                        proOld = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == pId).FirstOrDefault();
                        //添加项目
                        msgPro += " 项目名称：  " + proOld.PROJECT_MANAGEMENT_TITLE + "\r";// 项目 1
                        msgPro += "（一）项目进展" + "\r";
                        msgPro += flag + ")" + proWorkList[i].PROJECT_WORKRECORD_TITLE + "\r";// 1) 工作记录01
                        flag += 1;
                    }
                    else
                    {
                        Guid? pId = proWorkList[i].PROJECT_MANAGEMENT_ID;
                        proNew = projectManagementRepository.GetModel(r => r.PROJECT_MANAGEMENT_ID == pId).FirstOrDefault();
                        if (proOld.PROJECT_MANAGEMENT_ID == proNew.PROJECT_MANAGEMENT_ID)
                        {
                            msgPro += flag + ")" + proWorkList[i].PROJECT_WORKRECORD_TITLE + "\r";// 1) 工作记录01
                            flag += 1;
                        }
                        else
                        {
                            msgPro += "（二）下一步计划" + "\r";
                            flag = 1;
                            msgPro += " · " + proOld.PROJECT_MANAGEMENT_TITLE + "\r";// 项目 1
                            msgPro += "（一）项目进展" + "\r";
                            msgPro += flag + ")" + proWorkList[i].PROJECT_WORKRECORD_TITLE + "\r";// 1) 工作记录01
                            flag += 1;
                        }
                    }


                    if (i == proWorkList.Count() - 1)
                    {
                        msgPro += "（二）下一步计划" + "\r";
                    }
                }

                #endregion

                #region 运维管理 写入 WORD

                string msgYunWei = "";
                flag = 1;

                PROJECT_MAINTENANCE_APPOPS yunWeiOld = new PROJECT_MAINTENANCE_APPOPS();
                PROJECT_MAINTENANCE_APPOPS yunWeiNew = new PROJECT_MAINTENANCE_APPOPS();
                for (int i = 0; i < yunWeiWorkList.Count(); i++)
                {
                    if (i == 0)
                    {
                        Guid pId = yunWeiWorkList[i].RECORD_OPERATION_ID;
                        yunWeiOld = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == pId).FirstOrDefault();
                        //添加项目
                        msgYunWei += " 项目名称：   " + yunWeiOld.APPOPS_NAME + "\r";// 项目 1
                        msgYunWei += "（一）项目进展" + "\r";
                        msgYunWei += flag + ")" + yunWeiWorkList[i].RECORD_NAME + "\r";// 1) 工作记录01
                        flag += 1;
                    }
                    else
                    {
                        Guid pId = yunWeiWorkList[i].RECORD_OPERATION_ID;
                        yunWeiNew = projectMaintenanceAppopsRepository.GetModel(r => r.APPOPS_ID == pId).FirstOrDefault();
                        if (yunWeiOld.APPOPS_ID == yunWeiNew.APPOPS_ID)
                        {
                            msgYunWei += flag + ")" + yunWeiWorkList[i].RECORD_NAME + "\r";// 1) 工作记录01
                            flag += 1;
                        }
                        else
                        {
                            msgYunWei += "（二）下一步计划" + "\r";
                            flag = 1;
                            msgYunWei += " · " + proOld.PROJECT_MANAGEMENT_TITLE + "\r";// 项目 1
                            msgYunWei += "（一）项目进展" + "\r";
                            msgYunWei += flag + ")" + proWorkList[i].PROJECT_WORKRECORD_TITLE + "\r";// 1) 工作记录01
                            flag += 1;
                        }
                    }


                    if (i == yunWeiWorkList.Count() - 1)
                    {
                        msgYunWei += "（二）下一步计划" + "\r";
                    }
                }

                #endregion


                document.Replace("[项目实施进度]", msgPro, true, true);

                document.Replace("[运维实施进度]", msgYunWei, true, true);

                document.Replace("[日期]", DateTime.Now.ToString("yyyy年MM月dd日"), true, true);

                CreateTemp();
                //Guid guidFileName = Guid.NewGuid();
                string path = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Temp\" + fileShowName + ".doc";

                document.SaveToFile(path, FileFormat.Doc);

                DownLoadFile(path, "Temp", fileShowName + ".doc");
                
                LoggerFactory.Instance.Logger_Info(CurrentUser.UserName + " " + DateTime.Now + " " + "生成月报模板");

                DelTempFile();

                return this.RedirectToAction("Index", "Monthly", new { area = "ProjectManageArea", flag = "ExecuteTrue" });
            }
            catch (Exception ex)
            {
                LoggerFactory.Instance.Logger_Warn(CurrentUser.UserName+" "+DateTime.Now+" "+ "生成月报模板失败！ 信息："+ex.Message);
                return this.RedirectToAction("Index", "Monthly", new { area = "ProjectManageArea", flag = "ExecuteFalse", info = ex.Message });
            }
        }


        private void DownLoadFile(string filePath, string type, string fileName)
        {

            string fileFullPath = Path.Combine(ConfigurationManager.AppSettings["UpLoadPath"], type, fileName);

            //filePath = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["AttachmentPath"] + filePath);
            FileStream fs = new FileStream(fileFullPath, FileMode.Open);
            byte[] bytes = new byte[(int)fs.Length];
            fs.Read(bytes, 0, bytes.Length);
            fs.Close();
            Response.Charset = "UTF-8";
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("UTF-8");
            Response.ContentType = "application/octet-stream";

            //Response.AddHeader("Content-Disposition", "attachment; filename=" + Server.UrlEncode(filePath));
            //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(ToUTF8(filePath.Split('\\')[filePath.Split('\\').Length - 1]), System.Text.Encoding.GetEncoding("GB2312")));
            //Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filePath.Split('\\')[filePath.Split('\\').Length - 1], System.Text.Encoding.GetEncoding("GB2312")));
            Response.AddHeader("Content-Disposition", "attachment; filename=" + HttpUtility.UrlEncode(filePath.Split('\\')[filePath.Split('\\').Length - 1], System.Text.Encoding.GetEncoding("UTF-8")));
            Response.BinaryWrite(bytes);
            Response.Flush();
            Response.End();

        }

        private string ToUTF8(string name)
        {
            StringBuilder sb=new StringBuilder();
            for (int i = 0; i < name.Length; i++)
            {
                char c = name[i];
                if (c>=0 && c<=255)
                {
                    sb.Append(c);
                }
                else
                {
                    byte[] b;
                    try
                    {
                        b = Encoding.UTF8.GetBytes(c.ToString());
                    }
                    catch (Exception)
                    {
                        b=new byte[0];
                    }
                    for (int j = 0; j < b.Length; j++)
                    {
                        int k = b[j];
                        if (k<0)
                        {
                            k += 256;
                            sb.Append("%" + Convert.ToString(k, 16).ToUpper());
                        }
                    }
                }
            }
            return sb.ToString();
        }

        private void CreateTemp()
        {
            string path = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Temp\";
            if (Directory.Exists(path)==false)
            {
                Directory.CreateDirectory(path);
            }
        }

        private void DelTempFile()
        {
            string path = ConfigurationManager.AppSettings["UpLoadPath"] + @"\Temp\";
            DirectoryInfo di=new DirectoryInfo(path);
            di.Delete(true);
        }


    }
}

